package com.sdgakj.web.family;

import com.google.common.collect.Maps;
import com.sdgakj.entity.Family;
import com.sdgakj.service.account.ShiroDbRealm;
import com.sdgakj.service.family.FamilyService;
import com.sdgakj.service.user.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.Servlets;

import javax.servlet.ServletRequest;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Map;

@Controller
@RequestMapping(value = "/family")
public class FamilyController {

    private static Logger logger = LoggerFactory.getLogger(FamilyController.class);

    @Autowired
    private FamilyService familyService;

    @Autowired
    private UserService userService;

    private static final String PAGE_SIZE = "10";

    private static Map<String, String> sortTypes = Maps.newLinkedHashMap();

    static {
        sortTypes.put("auto", "自动");
    }

    /**
     * 查询家族列表
     *
     * @param pageNumber 页号
     * @param pageSize   页数
     * @param sortType   排序字段
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(@RequestParam(value = "page", defaultValue = "1") int pageNumber,
                       @RequestParam(value = "page.size", defaultValue = PAGE_SIZE) int pageSize,
                       @RequestParam(value = "sortType", defaultValue = "auto") String sortType, Model model,
                       ServletRequest request) {
        logger.info("query the family list...");
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        //当前登录用户
       /* ShiroDbRealm.ShiroUser shiroUser = (ShiroDbRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
        Long id = shiroUser.id;
        System.out.println(id+"----------------------shiroID");*/

        Page<Family> families = familyService.getFamilis(searchParams, pageNumber, pageSize, sortType);
        model.addAttribute("families", families);
        model.addAttribute("sortType", sortType);
        model.addAttribute("sortTypes", sortTypes);
        // 将搜索条件编码成字符串，用于排序，分页的URL
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
        return "family/familyList";
    }

    /**
     * 跳转修改家族页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
    public String updateFamily(@PathVariable("id") Long id, Model model) {
        Family family = familyService.getFmilyById(id);
        model.addAttribute("family", family);
        model.addAttribute("action", "update");
        return "family/familyForm";
    }

    /**
     * 修改家族信息
     * @param entity
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String updateFamily(@ModelAttribute("family") Family entity, RedirectAttributes redirectAttributes) {
        logger.info("update the family...");
        //根据id查出家族数据后，更新家族名、描述、更新时间
        Family familyById = familyService.getFamilyById(entity.getId());
        Timestamp ts = new Timestamp(new Date().getTime());
        familyById.setUpdatetime(ts);
        familyById.setfName(entity.getfName());
        familyById.setfDesp(entity.getfDesp());
        familyService.updateFamily(familyById);
        redirectAttributes.addAttribute("message", "修改成功！");
        return "redirect:/family/list";
    }

    /**
     * 删除家族信息
     * @param id
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public String delete(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
        familyService.deleteFamily(id);
        redirectAttributes.addFlashAttribute("message", "删除成功！");
        return "redirect:/family/list";
    }

    /**
     * Ajax请求校验fName是否唯一。
     *
     * @param fName
     * @param userId
     * @return
     */
    @RequestMapping(value = "/checkfName")
    @ResponseBody
    public String checkMobile(@RequestParam("fName") String fName,
                              @RequestParam(value = "userId", defaultValue = "") String userId) {
        Family family = null;
        if (StringUtils.isNotBlank(userId)) {
            family = familyService.getFmilyById(Long.valueOf(userId));
        }
//        System.out.println(fName + "-------校验fName");
        Family checkfamily = null;
        checkfamily = familyService.getFamilyByFamilyName(fName); //普通用户的表
        if (checkfamily == null) {
            return "true";
        } else {
            if (family != null && checkfamily.getCreatetime().equals(family.getCreatetime())) {
                return "true";
            }
            return "false";
        }
    }


    /**
     * 跳转新增页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/createform", method = RequestMethod.GET)
    public String addRole(Model model) {
        model.addAttribute("action", "create");
        return "family/familyForm";
    }

    /**
     * 添加家族信息
     * @param entity
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public String createFamily(Family entity, RedirectAttributes redirectAttributes) {
        logger.info("save the family");

        Timestamp ts = new Timestamp(new Date().getTime());

        entity.setCreatetime(ts);
        entity.setUpdatetime(ts);
        ShiroDbRealm.ShiroUser shiroUser = (ShiroDbRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
        entity.setUserId(shiroUser.id);//设置关联用户id
        familyService.saveFamily(entity);
        redirectAttributes.addAttribute("message", "添加成功！");
        return "redirect:/family/list";
    }
}
